<?php
/**
 * @file			apiFormat.class.php
 * @CopyRight		(C)1996-2099 SINA Inc.
 * @Project			自游网
 * @Author			liujz <jianzhou@staff.sina.com.cn>
 * @Create Date:	2011-12-29
 * @Modified By:	jianzhou/2011-12-29
 * @Brief			API 输出格式化
 */

class apiFormat_class 
{
	var $cfg 		= array();
	var $pregCfg 	= array();
	
	
	//内置的，不同节点的命名配置
	var $allCfg = array
	(
		// 用户节点
		"user_s" 	=> array('id','nickname','face_s'),
		"user_m" 	=> array('id','nickname','face_s','gender','fans','follows','youji','pms','medal','photo','money','exp','level','location','create_time'),
	
		// 景点节点
		"spot_s" 	=> array('id','name','cover_thumb'),
		"spot_m" 	=> array('id','name','cover_thumb','province_id','province_name','city_id','city_name','lat','lng','want_to_user','have_been_user','is_dest'),
	
		// 游记节点
		"yj_s" => array('id','title'),
		"yj_m" => array('id','title','users_at','create_time','comment_count','like_count','whether_liked')
	);

	
	//构造方法
	function apiRstFormat($strCfg=""){
		if ($strCfg) { $this->init($strCfg); }
	}

	
	/**
	 * 解析传递配置
	 * @param $strCfg
	 */
	function init($strCfg)
	{
		$this->cfg 		= array();
		$this->pregCfg 	= array();

		parse_str(strtolower($strCfg), $cfgTmp);
		if (!is_array($cfgTmp) || empty($cfgTmp) ){
			vApi::throwException('110013', '无效的返回格式配置');
		}
		
		foreach($cfgTmp as $k=>$v)
		{
			if (isset($this->allCfg[$v]))
			{
				$kk = str_replace("*","[^/]+",$k);
				if ($kk == $k){
					$this->cfg[$kk] = array_flip($this->allCfg[$v]);
				}else{
					$this->pregCfg[";^".$kk."\$;sim"] = array_flip($this->allCfg[$v]);
				}
			} else if ( '/_custom'==$k ) {	// 根目录自定义返回
				$this->cfg['/'] = array_flip( explode(',',$v) );
			} 
			else if ( '/_custom'==substr($k,-8) ) 	// 自定义返回
			{
				$kk   = str_replace("*","[^/]+",$k);
				$tmpK = substr($kk,0,-8);
				$this->pregCfg[";^".$tmpK."\$;sim"] = array_flip( explode(',',$v) );
			}else{
				vApi::throwException('110013',	'无效的返回格式配置['.$v.']');
			}
		}
		return $this;
	}


	/**
	 * 格式化函数
	 * @param $rst
	 * @param $preKey
	 */
	function doFormat($rst, $preKey='')
	{
		if (!$preKey && isset($this->cfg["/"])){
			$rst = is_array($rst) ? array_intersect_key($rst , $this->cfg["/"]) : $rst;
		}

		foreach($rst as $k=>$v)
		{
			$treeKey = $preKey."/".$k;
			$rule 	 = $this->inRule($treeKey);
			if ($rule) { $v=$rst[$k]=(is_array($rst)?array_intersect_key($v,$rule):$rst); }

			// 递归调用
			if (is_array($v)){ $rst[$k]=$this->doFormat($v,$treeKey);}
		}
		return $rst;
	}


	//判断是否符合条件的节点
	function inRule($treeKey)
	{
		if (isset($this->cfg[$treeKey])){
			return $this->cfg[$treeKey];
		}
		
		if (!empty($this->pregCfg)) 
		{
			foreach ($this->pregCfg as $pk=>$pv){
				if (preg_match($pk, $treeKey)){ return $pv; }
			}
		}
		return false;
	}
}